package menus;
// File: BranchController.java

import gui.CustomTable;
import gui.CustomTableModel;
import gui.ExceptionListener;
import gui.MainView;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*; 

import database.ManagerData;
import database.PosData;

import java.sql.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;


/*
 * BranchController is a control class that handles action events 
 * on the Branch Admin menu. It also updates the GUI based on 
 * which menu item the user selected. This class contains the following 
 * inner classes: BranchInsertDialog, BranchUpdateDialog, and 
 * BranchDeleteDialog. BranchInsertDialog is a dialog box that allows a 
 * user to insert a branch. BranchUpdateDialog is a dialog box that allows 
 * a user to update the name of a branch. BranchDeleteDialog is a dialog box 
 * that allows a user to delete a branch.
 *
 * BranchController implements the ExceptionListener interface which
 * allows it to be notified of any Exceptions that occur in BranchModel
 * (BranchModel contains the database transaction functions). It is defined
 * in BranchModel.java. The ExceptionListener interface is defined in 
 * ExceptionListener.java. When an Exception occurs in BranchModel, 
 * BranchController will update the status text area of MvbView. 
 */
public class ManagerMenu extends MenuSuperclass implements ActionListener, ExceptionListener
{
	private ManagerData items = null;
	private PosData transaction = null;


	public ManagerMenu(MainView mvb)
	{
		this.mv = mvb;
		items = new ManagerData();
		transaction = new PosData();

		// register to receive exception events from branch
		items.addExceptionListener(this);
	}


	/*
	 * This event handler gets called when the user makes a menu
	 * item selection.
	 */ 
	public void actionPerformed(ActionEvent e)
	{
		String actionCommand = e.getActionCommand();

		// you cannot use == for string comparisons
		if (actionCommand.equals("Set Delivered"))
		{
			DateDialog dDialog = new DateDialog(mv);
			dDialog.pack();
			mv.centerWindow(dDialog);
			dDialog.setVisible(true);

			return; 
		}

		if (actionCommand.equals("Add Item"))
		{
			ItemInsertDialog iDialog = new ItemInsertDialog(mv);
			iDialog.pack();
			mv.centerWindow(iDialog);
			iDialog.setVisible(true);
			return; 
		}

		if (actionCommand.equals("Update Stock"))
		{
			ItemUpdateDialog uDialog = new ItemUpdateDialog(mv);
			uDialog.pack();
			mv.centerWindow(uDialog);
			uDialog.setVisible(true);
			return; 
		}

		if (actionCommand.equals("Show Items"))
		{
			showAllItems();
			return; 
		}

		if (actionCommand.equals("Edit Items"))
		{
			editAllItems();
			return; 
		}	

		if (actionCommand.equals("Sales Report"))
		{
			// get date as text string yyyy-mm-dd

			SalesReportDialog sDialog = new SalesReportDialog(mv);
			sDialog.pack();
			mv.centerWindow(sDialog);
			sDialog.setVisible(true);
			return; 

		}

		if (actionCommand.equals("Best Sellers"))
		{
			// get date as text string yyyy-mm-dd
			// get int to limit # of records returned
			// get and display that many records ordered by qty sold
			BestSellersDialog bDialog = new BestSellersDialog(mv);
			bDialog.pack();
			mv.centerWindow(bDialog);
			bDialog.setVisible(true);
			return; 


		}
	}


	/*
	 * This method displays all branches in a non-editable JTable
	 */
	private void showAllItems()
	{
		ResultSet rs = items.showBranch();

		// CustomTableModel maintains the result set's data, e.g., if  
		// the result set is updatable, it will update the database
		// when the table's data is modified.  
		CustomTableModel model = new CustomTableModel(items.getConnection(), rs);
		CustomTable data = new CustomTable(model);

		// register to be notified of any exceptions that occur in the model and table
		model.addExceptionListener(this);
		data.addExceptionListener(this);

		// Adds the table to the scrollpane.
		// By default, a JTable does not have scroll bars.
		mv.addTable(data);

	}

	private void showSalesReport(ResultSet rs, Date ldate)

	{


		// CustomTableModel maintains the result set's data, e.g., if  
		// the result set is updatable, it will update the database
		// when the table's data is modified.  
		CustomTableModel model = new CustomTableModel(items.getConnection(), rs);
		CustomTable data = new CustomTable(model);

		// register to be notified of any exceptions that occur in the model and table
		model.addExceptionListener(this);
		data.addExceptionListener(this);

		// Adds the table to the scrollpane.
		// By default, a JTable does not have scroll bars.
		mv.addTable(data);

		String msg;
		int qty = 0;
		double tot = 0;

		try {
			rs.beforeFirst();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			while (rs.next()) {
				qty = qty+rs.getInt(4);
				tot = tot+rs.getDouble(5);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}


		msg = "Daily Sales for " + ldate + "\nTotal Units: " + qty + "\nTotal Sales: $" + tot;

		message(msg, mv.georgeIcon);

	}

	private void bestSellers(ResultSet rs)

	{


		// CustomTableModel maintains the result set's data, e.g., if  
		// the result set is updatable, it will update the database
		// when the table's data is modified.  
		CustomTableModel model = new CustomTableModel(items.getConnection(), rs);
		CustomTable data = new CustomTable(model);

		// register to be notified of any exceptions that occur in the model and table
		model.addExceptionListener(this);
		data.addExceptionListener(this);

		// Adds the table to the scrollpane.
		// By default, a JTable does not have scroll bars.
		mv.addTable(data);



		try {
			rs.beforeFirst();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}





	}


	/*
	 * This method displays all branches in an editable JTable
	 */
	private void editAllItems()
	{
		ResultSet rs = items.editBranch();
		CustomTableModel model = new CustomTableModel(items.getConnection(), rs);
		CustomTable data = new CustomTable(model);
		model.addExceptionListener(this);
		data.addExceptionListener(this);
		mv.addTable(data);
	}



	/*
	 * This class creates a dialog box for inserting a branch.
	 */
	class ItemInsertDialog extends JDialog implements ActionListener
	{
		private JTextField upc = new JTextField(10);
		private JTextField title = new JTextField(50);
		private JTextField type = new JTextField(50);
		private JTextField category = new JTextField(50);
		private JTextField company = new JTextField(50);
		private JTextField year = new JTextField(4);
		private JTextField price = new JTextField(10);
		private JTextField stock = new JTextField(10);


		/*
		 * Constructor. Creates the dialog's GUI.
		 */
		public ItemInsertDialog(JFrame parent)
		{
			super(parent, "Add Item", true);
			setResizable(false);

			JPanel contentPane = new JPanel(new BorderLayout());
			setContentPane(contentPane);
			contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

			// this panel will contain the text field labels and the text fields.
			JPanel inputPane = new JPanel();
			inputPane.setBorder(BorderFactory.createCompoundBorder(
					new TitledBorder(new EtchedBorder(), "Item Details"), 
					new EmptyBorder(5, 5, 5, 5)));

			// add the text field labels and text fields to inputPane
			// using the GridBag layout manager

			GridBagLayout gb = new GridBagLayout();
			GridBagConstraints c = new GridBagConstraints();
			inputPane.setLayout(gb);

			JLabel label= new JLabel("UPC: ", SwingConstants.RIGHT);	    
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(0, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(0, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(upc, c);
			inputPane.add(upc);

			label = new JLabel("Album Title: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(title, c);
			inputPane.add(title);

			label = new JLabel("Type: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(type, c);
			inputPane.add(type);

			label = new JLabel("Category: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(category, c);
			inputPane.add(category);

			label = new JLabel("Company: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(company, c);
			inputPane.add(company);

			label = new JLabel("Year: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(year, c);
			inputPane.add(year);

			label = new JLabel("Price: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(price, c);
			inputPane.add(price);

			label = new JLabel("Stock: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(stock, c);
			inputPane.add(stock);

			// when the return key is pressed in the last field
			// of this form, the action performed by the ok button
			// is executed
			stock.addActionListener(this);
			stock.setActionCommand("OK");

			// panel for the OK and cancel buttons
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
			buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

			JButton OKButton = new JButton("OK");
			JButton cancelButton = new JButton("Cancel");
			OKButton.addActionListener(this);
			OKButton.setActionCommand("OK");
			cancelButton.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});

			// add the buttons to buttonPane
			buttonPane.add(Box.createHorizontalGlue());
			buttonPane.add(OKButton);
			buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
			buttonPane.add(cancelButton);

			contentPane.add(inputPane, BorderLayout.CENTER);
			contentPane.add(buttonPane, BorderLayout.SOUTH);

			addWindowListener(new WindowAdapter() 
			{
				public void windowClosing(WindowEvent e)
				{
					dispose();
				}
			});
		}


		/*
		 * Event handler for the OK button in BranchInsertDialog
		 */ 
		public void actionPerformed(ActionEvent e)
		{
			String actionCommand = e.getActionCommand();

			if (actionCommand.equals("OK"))
			{
				if (validateInsert() != VALIDATIONERROR)
				{
					dispose();
				}
				else
				{
					Toolkit.getDefaultToolkit().beep();

					// display a popup to inform the user of the validation error
					JOptionPane errorPopup = new JOptionPane();
					errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
				}	
			}
		}


		/*
		 * Validates the text fields in BranchInsertDialog and then
		 * calls branch.insertBranch() if the fields are valid.
		 * Returns the operation status, which is one of OPERATIONSUCCESS, 
		 * OPERATIONFAILED, VALIDATIONERROR.
		 */ 
		private int validateInsert()
		{
			try
			{
				Integer iupc;
				String ititle;
				String itype;
				String icategory;
				String icompany;
				Integer iyear = 1969;
				Double iprice = 10.99;
				Integer istock = 5;

				if (upc.getText().trim().length() != 0)
				{
					iupc = Integer.valueOf(upc.getText().trim());

					// check for duplicates
					if (items.findItem(iupc.intValue()))
					{
						Toolkit.getDefaultToolkit().beep();
						mv.updateStatusBar("Branch " + iupc.toString() + " already exists!");
						return OPERATIONFAILED; 
					}
				}
				else
				{
					return VALIDATIONERROR; 
				}


				if (title.getText().trim().length() != 0)
				{
					ititle = title.getText().trim();
				}
				else
				{
					ititle = "Default"; 
				}

				if (type.getText().trim().length() != 0)
				{
					itype = type.getText().trim();
				}
				else
				{
					itype = "Default"; 
				}

				if (category.getText().trim().length() != 0)
				{
					icategory = category.getText().trim();
				}
				else
				{
					icategory = "Default"; 
				}

				if (company.getText().trim().length() != 0)
				{
					icompany = company.getText().trim();
				}
				else
				{
					icompany = "Default"; 
				}

				if (year.getText().trim().length() != 0)
				{
					iyear = Integer.valueOf(year.getText().trim());
				}
				else
				{
					iyear = 0; 
				}

				if (price.getText().trim().length() != 0)
				{
					iprice = Double.valueOf(price.getText().trim());
				}
				else
				{
					iprice = 0.0; 
				}

				if (stock.getText().trim().length() != 0)
				{
					istock = Integer.valueOf(stock.getText().trim());
				}
				else
				{
					istock = 0; 
				}

				mv.updateStatusBar("Inserting item #" + iupc);

				if (items.insertItem(iupc, ititle, itype, icategory, icompany, iyear, iprice, istock))
				{
					mv.updateStatusBar("Success");
					editAllItems();
					return OPERATIONSUCCESS; 
				}
				else
				{
					Toolkit.getDefaultToolkit().beep();
					mv.updateStatusBar("Fail");
					return OPERATIONFAILED; 
				}
			}
			catch (NumberFormatException ex)
			{
				// this exception is thrown when a string 
				// cannot be converted to a number
				return VALIDATIONERROR; 
			}
		}
	}


	class SalesReportDialog extends JDialog implements ActionListener
	{
		private JTextField date = new JTextField(12);

		/*
		 * Constructor. Creates the dialog's GUI.
		 */
		public SalesReportDialog(JFrame parent)
		{
			super(parent, "Sales Report", true);
			setResizable(false);

			JPanel contentPane = new JPanel(new BorderLayout());
			setContentPane(contentPane);
			contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

			// this panel will contain the text field labels and the text fields.
			JPanel inputPane = new JPanel();
			inputPane.setBorder(BorderFactory.createCompoundBorder(
					new TitledBorder(new EtchedBorder(), "Daily Sales"), 
					new EmptyBorder(5, 5, 5, 5)));

			// add the text field labels and text fields to inputPane
			// using the GridBag layout manager

			GridBagLayout gb = new GridBagLayout();
			GridBagConstraints c = new GridBagConstraints();
			inputPane.setLayout(gb);

			JLabel label= new JLabel("Date: ", SwingConstants.RIGHT);	    
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(0, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(0, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(date, c);
			date.setText("2013-08-13");
			date.selectAll();

			inputPane.add(date);



			// when the return key is pressed in the last field
			// of this form, the action performed by the ok button
			// is executed
			date.addActionListener(this);
			date.setActionCommand("OK");

			// panel for the OK and cancel buttons
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
			buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

			JButton OKButton = new JButton("OK");
			JButton cancelButton = new JButton("Cancel");
			OKButton.addActionListener(this);
			OKButton.setActionCommand("OK");
			cancelButton.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});

			// add the buttons to buttonPane
			buttonPane.add(Box.createHorizontalGlue());
			buttonPane.add(OKButton);
			buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
			buttonPane.add(cancelButton);

			contentPane.add(inputPane, BorderLayout.CENTER);
			contentPane.add(buttonPane, BorderLayout.SOUTH);

			addWindowListener(new WindowAdapter() 
			{
				public void windowClosing(WindowEvent e)
				{
					dispose();
				}
			});
		}


		/*
		 * Event handler for the OK button in BranchInsertDialog
		 */ 
		public void actionPerformed(ActionEvent e)
		{
			String actionCommand = e.getActionCommand();

			if (actionCommand.equals("OK"))
			{
				if (validateDate() != VALIDATIONERROR)
				{

				}
				else
				{
					Toolkit.getDefaultToolkit().beep();

					// display a popup to inform the user of the validation error
					JOptionPane errorPopup = new JOptionPane();
					errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
				}	
			}
		}

		private Date convertToDate(String s) {
			DateFormat d = new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date date = null;
			try {
				date = d.parse(s);
			} catch (ParseException e) {
				System.out.println("somethingsomethingparsedate");
			}
			java.sql.Date sqlDate = new Date(date.getTime());
			return sqlDate;
		}


		/*
		 * Validates the text fields in BranchInsertDialog and then
		 * calls branch.insertBranch() if the fields are valid.
		 * Returns the operation status, which is one of OPERATIONSUCCESS, 
		 * OPERATIONFAILED, VALIDATIONERROR.
		 */ 
		private int validateDate()
		{
			Date ldate;




			if (date.getText().trim().length() != 0)
			{
				ldate = convertToDate(date.getText().trim());
				dispose();
				showSalesReport(items.salesReport(ldate), ldate);
				return OPERATIONSUCCESS;
			}
			else
			{
				mv.updateStatusBar("Enter valid date: YYYY-MM-DD");
				return VALIDATIONERROR;

			}


		}
	}




	class DateDialog extends JDialog implements ActionListener
	{
		private JTextField date = new JTextField(12);

		/*
		 * Constructor. Creates the dialog's GUI.
		 */
		public DateDialog(JFrame parent)
		{
			super(parent, "Set Delivered", true);
			setResizable(false);

			JPanel contentPane = new JPanel(new BorderLayout());
			setContentPane(contentPane);
			contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

			// this panel will contain the text field labels and the text fields.
			JPanel inputPane = new JPanel();
			inputPane.setBorder(BorderFactory.createCompoundBorder(
					new TitledBorder(new EtchedBorder(), "Set Delivered Date"), 
					new EmptyBorder(5, 5, 5, 5)));

			// add the text field labels and text fields to inputPane
			// using the GridBag layout manager

			GridBagLayout gb = new GridBagLayout();
			GridBagConstraints c = new GridBagConstraints();
			inputPane.setLayout(gb);

			JLabel label= new JLabel("Receipt #: ", SwingConstants.RIGHT);	    
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(0, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(0, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(date, c);

			inputPane.add(date);



			// when the return key is pressed in the last field
			// of this form, the action performed by the ok button
			// is executed
			date.addActionListener(this);
			date.setActionCommand("OK");

			// panel for the OK and cancel buttons
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
			buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

			JButton OKButton = new JButton("OK");
			JButton cancelButton = new JButton("Cancel");
			OKButton.addActionListener(this);
			OKButton.setActionCommand("OK");
			cancelButton.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});

			// add the buttons to buttonPane
			buttonPane.add(Box.createHorizontalGlue());
			buttonPane.add(OKButton);
			buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
			buttonPane.add(cancelButton);

			contentPane.add(inputPane, BorderLayout.CENTER);
			contentPane.add(buttonPane, BorderLayout.SOUTH);

			addWindowListener(new WindowAdapter() 
			{
				public void windowClosing(WindowEvent e)
				{
					dispose();
				}
			});
		}


		/*
		 * Event handler for the OK button in BranchInsertDialog
		 */ 
		public void actionPerformed(ActionEvent e)
		{
			String actionCommand = e.getActionCommand();

			if (actionCommand.equals("OK"))
			{
				if (validateDate() != VALIDATIONERROR)
				{

				}
				else
				{
					Toolkit.getDefaultToolkit().beep();

					// display a popup to inform the user of the validation error
					JOptionPane errorPopup = new JOptionPane();
					errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
				}	
			}
		}

		private Date convertToDate(String s) {
			DateFormat d = new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date date = null;
			try {
				date = d.parse(s);
			} catch (ParseException e) {
				System.out.println("somethingsomethingparsedate");
			}
			java.sql.Date sqlDate = new Date(date.getTime());
			return sqlDate;
		}


		/*
		 * Validates the text fields in BranchInsertDialog and then
		 * calls branch.insertBranch() if the fields are valid.
		 * Returns the operation status, which is one of OPERATIONSUCCESS, 
		 * OPERATIONFAILED, VALIDATIONERROR.
		 */ 
		private int validateDate()
		{
			int ldate;




			if (date.getText().trim().length() != 0)
			{
				ldate = Integer.valueOf(date.getText().trim());
				dispose();
				transaction.setDelDate(ldate);
				return OPERATIONSUCCESS;
			}
			else
			{
				mv.updateStatusBar("Enter valid date: YYYY-MM-DD");
				return VALIDATIONERROR;

			}


		}
	}


	class BestSellersDialog extends JDialog implements ActionListener
	{
		private JTextField date = new JTextField(12);
		private JTextField num = new JTextField(5);

		/*
		 * Constructor. Creates the dialog's GUI.
		 */
		public BestSellersDialog(JFrame parent)
		{
			super(parent, "Best Sellers", true);
			setResizable(false);

			JPanel contentPane = new JPanel(new BorderLayout());
			setContentPane(contentPane);
			contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

			// this panel will contain the text field labels and the text fields.
			JPanel inputPane = new JPanel();
			inputPane.setBorder(BorderFactory.createCompoundBorder(
					new TitledBorder(new EtchedBorder(), "Daily Sales"), 
					new EmptyBorder(5, 5, 5, 5)));

			// add the text field labels and text fields to inputPane
			// using the GridBag layout manager

			GridBagLayout gb = new GridBagLayout();
			GridBagConstraints c = new GridBagConstraints();
			inputPane.setLayout(gb);

			JLabel label= new JLabel("Date: ", SwingConstants.RIGHT);	    
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(0, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(0, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(date, c);
			date.setText("2013-08-13");
			date.selectAll();

			inputPane.add(date);

			label= new JLabel("Number of Items: ", SwingConstants.RIGHT);	    
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(0, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(0, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(num, c);
			num.setText("1");
			num.selectAll();

			inputPane.add(num);


			// when the return key is pressed in the last field
			// of this form, the action performed by the ok button
			// is executed
			date.addActionListener(this);
			date.setActionCommand("OK");

			// panel for the OK and cancel buttons
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
			buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

			JButton OKButton = new JButton("OK");
			JButton cancelButton = new JButton("Cancel");
			OKButton.addActionListener(this);
			OKButton.setActionCommand("OK");
			cancelButton.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});

			// add the buttons to buttonPane
			buttonPane.add(Box.createHorizontalGlue());
			buttonPane.add(OKButton);
			buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
			buttonPane.add(cancelButton);

			contentPane.add(inputPane, BorderLayout.CENTER);
			contentPane.add(buttonPane, BorderLayout.SOUTH);

			addWindowListener(new WindowAdapter() 
			{
				public void windowClosing(WindowEvent e)
				{
					dispose();
				}
			});
		}


		/*
		 * Event handler for the OK button in BranchInsertDialog
		 */ 
		public void actionPerformed(ActionEvent e)
		{
			String actionCommand = e.getActionCommand();

			if (actionCommand.equals("OK"))
			{
				if (validateDate() != VALIDATIONERROR)
				{

				}
				else
				{
					Toolkit.getDefaultToolkit().beep();

					// display a popup to inform the user of the validation error
					JOptionPane errorPopup = new JOptionPane();
					errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
				}	
			}
		}


		/*
		 * Validates the text fields in BranchInsertDialog and then
		 * calls branch.insertBranch() if the fields are valid.
		 * Returns the operation status, which is one of OPERATIONSUCCESS, 
		 * OPERATIONFAILED, VALIDATIONERROR.
		 */ 
		private int validateDate()
		{
			Date ldate;
			int lnum = Integer.valueOf(num.getText().trim());





			if (date.getText().trim().length() != 0)
			{
				ldate = convertToDate(date.getText().trim());
				dispose();
				bestSellers(items.bestSellers(ldate, lnum));
				return OPERATIONSUCCESS;
			}
			else
			{
				mv.updateStatusBar("Enter valid date: YYYY-MM-DD");
				return VALIDATIONERROR;

			}


		}
	}


	private Date convertToDate(String s) {
		DateFormat d = new SimpleDateFormat("yyyy-MM-dd");
		java.util.Date date = null;
		try {
			date = d.parse(s);
		} catch (ParseException e) {
			System.out.println("somethingsomethingparsedate");
		}
		java.sql.Date sqlDate = new Date(date.getTime());
		return sqlDate;
	}

	/*
	 * This class creates a dialog box for updating a branch.
	 */
	class ItemUpdateDialog extends JDialog implements ActionListener
	{
		private JTextField upc = new JTextField(4);
		private JTextField stock = new JTextField(10);
		private JTextField price = new JTextField(10);

		/*
		 * Constructor. Creates the dialog's GUI.
		 */
		public ItemUpdateDialog(JFrame parent)
		{
			super(parent, "Update Stock", true);
			setResizable(false);

			JPanel contentPane = new JPanel(new BorderLayout());
			setContentPane(contentPane);
			contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

			// this panel contains the text field labels and 
			// the text fields.
			JPanel inputPane = new JPanel();
			inputPane.setBorder(BorderFactory.createCompoundBorder(
					new TitledBorder(new EtchedBorder(), ""), 
					new EmptyBorder(5, 5, 5, 5)));

			// add the text field labels and text fields to inputPane
			// using the GridBag layout manager

			GridBagLayout gb = new GridBagLayout();
			GridBagConstraints c = new GridBagConstraints();
			inputPane.setLayout(gb);

			// create and place branch id label
			JLabel label= new JLabel("UPC: ", SwingConstants.RIGHT);	    
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(0, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);

			// place branch id field
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(0, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(upc, c);
			inputPane.add(upc);

			// create and place branch name label
			label = new JLabel("Adjust Price: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);

			// place branch name field
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(price, c);
			price.setText("New Price");
			inputPane.add(price);

			// create and place branch name label
			label = new JLabel("Adjust Stock: ", SwingConstants.RIGHT);
			c.gridwidth = GridBagConstraints.RELATIVE;
			c.insets = new Insets(5, 0, 0, 5);
			c.anchor = GridBagConstraints.EAST;
			gb.setConstraints(label, c);
			inputPane.add(label);

			// place branch name field
			c.gridwidth = GridBagConstraints.REMAINDER;
			c.insets = new Insets(5, 0, 0, 0);
			c.anchor = GridBagConstraints.WEST;
			gb.setConstraints(stock, c);
			stock.setText("+/- Quantity");
			inputPane.add(stock);

			// when the return key is pressed in the last field
			// of this form, the action performed by the ok button
			// is executed
			stock.addActionListener(this);
			stock.setActionCommand("OK");

			// panel for the OK and cancel buttons
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
			buttonPane.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 2));

			JButton OKButton = new JButton("OK");
			JButton cancelButton = new JButton("Cancel");
			OKButton.addActionListener(this);
			OKButton.setActionCommand("OK");
			cancelButton.addActionListener(new ActionListener()
			{
				public void actionPerformed(ActionEvent e)
				{
					dispose();
				}
			});

			// add buttons to buttonPane
			buttonPane.add(Box.createHorizontalGlue());
			buttonPane.add(OKButton);
			buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
			buttonPane.add(cancelButton);

			contentPane.add(inputPane, BorderLayout.CENTER);
			contentPane.add(buttonPane, BorderLayout.SOUTH);

			addWindowListener(new WindowAdapter() 
			{
				public void windowClosing(WindowEvent e)
				{
					dispose();
				}
			});
		}


		/*
		 * Event handler for the OK button in BranchUpdateDialog
		 */ 
		public void actionPerformed(ActionEvent e)
		{
			String actionCommand = e.getActionCommand();

			if (actionCommand.equals("OK"))
			{
				if (validateUpdate() != VALIDATIONERROR)
				{
					dispose();
				}
				else
				{
					Toolkit.getDefaultToolkit().beep();

					// display a popup to inform the user of the error
					JOptionPane errorPopup = new JOptionPane();
					errorPopup.showMessageDialog(this, "Invalid Input", "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		}


		/*
		 * Validates the text fields in BranchUpdateDialog and then
		 * calls branch.branchUpdate() if the fields are valid.
		 * Returns the operation status.
		 */ 
		private int validateUpdate()
		{
			try
			{
				int iupc;
				int istock;
				double iprice;

				if (upc.getText().trim().length() != 0)
				{
					iupc = Integer.valueOf(upc.getText().trim()).intValue();

					// check if branch exists
					if (!items.findItem(iupc))
					{
						Toolkit.getDefaultToolkit().beep();
						mv.updateStatusBar("Item " + iupc + " does not exist!");
						return OPERATIONFAILED; 
					}
				}
				else
				{
					return VALIDATIONERROR; 
				}


				if (stock.getText().trim().length() != 0 && !stock.getText().trim().equals("+/- Quantity"))
				{
					istock = Integer.valueOf(stock.getText().trim());

					mv.updateStatusBar("Adjusting Stock...");

					if (items.adjustStock(iupc, istock))
					{
						mv.updateStatusBar("Operation successful.");
						editAllItems();
						return OPERATIONSUCCESS;
					}
					else
					{
						Toolkit.getDefaultToolkit().beep();
						mv.updateStatusBar("Operation failed.");
						return OPERATIONFAILED;
					}
				}

				if (stock.getText().trim().length() != 0 && !price.getText().trim().equals("New Price"))
				{
					iprice = Double.valueOf(price.getText().trim());

					mv.updateStatusBar("Adjusting Price...");

					if (items.adjustPrice(iupc, iprice))
					{
						mv.updateStatusBar("Operation successful.");
						editAllItems();
						return OPERATIONSUCCESS;
					}
					else
					{
						Toolkit.getDefaultToolkit().beep();
						mv.updateStatusBar("Operation failed.");
						return OPERATIONFAILED;
					}


				}
				else
				{
					return VALIDATIONERROR; 
				}



			}
			catch (NumberFormatException ex)
			{
				return VALIDATIONERROR; 
			}
		}
	}
}
